<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/1 上午10:00
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/1 上午10:00
 * @FilePath: G:/chain-link-api-front-admin/src/views/currencyManagement\index.vue
 * @Description: 币种管理
-->
<template>
  <!-- 查询 -->
  <div class="queryBar">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item :label="$t('table.ChainName')" style="width: 250px; margin-bottom:0; margin-right: 20px">
            <el-input v-model.trim="queryParams.chainName" :placeholder="$t('global.PleaseInput') + $t('table.ChainName')" clearable />
          </el-form-item>
          <el-form-item :label="$t('table.ChainIdMainCoinType')" style="width: 400px; margin-bottom:0; margin-right: 20px">
            <el-input v-model.trim="queryParams.chainIdMainCoinType" :placeholder="$t('global.PleaseInput') + $t('table.ChainIdMainCoinType')" clearable />
          </el-form-item>
          <el-form-item :label="$t('table.Symbol')" style="width: 250px; margin-bottom:0; margin-right: 20px">
            <el-input v-model.trim="queryParams.symbol" :placeholder="$t('global.PleaseInput') + $t('table.Symbol')" clearable />
          </el-form-item>
          <el-form-item :label="$t('table.AddressCoinType')" style="width: 350px; margin-bottom:0; margin-right: 20px">
            <el-input v-model.trim="queryParams.addressCoinType" :placeholder="$t('global.PleaseInput') + $t('table.AddressCoinType')" clearable />
          </el-form-item>
          <el-form-item style="margin-bottom: 0">
            <el-button type="primary" :icon="Search" @click="onSubmit(queryParams.chainName, queryParams.chainIdMainCoinType, queryParams.symbol, queryParams.addressCoinType)">{{
                $t('button.Search')
              }}</el-button>
            <el-button type="default" :icon="Refresh" plain @click="onReset()">{{ $t('button.Reset') }}</el-button>
          </el-form-item>
        </el-form>

    <!--    查询按钮-->
    <div class="query_btns">
      <el-button type="primary" plain :icon="Plus" size="small" @click="handleClick('add')">{{
          $t('button.Add')
        }}
      </el-button>
    </div>
  </div>

  <el-table :data="tableData" stripe border style="width: 100%; " size="large" v-loading="loading" max-height="600px">
    <el-table-column prop="ChainName" :label="$t('table.ChainName')" width="150" align="center"/>
    <el-table-column prop="ChainId" :label="$t('table.ChainIdMainCoinType')" width="200" align="center"/>
    <el-table-column prop="Decimals" :label="$t('table.Decimals')" width="100" align="center"/>
    <el-table-column prop="Symbol" :label="$t('table.Symbol')" width="150" align="center"/>
    <el-table-column prop="TotalSupply" :label="$t('table.TotalIssuance')" width="400" align="center"/>
    <el-table-column prop="Address" :label="$t('table.AddressCoinType')" width="400" align="center"/>
    <el-table-column fixed="right" :label="$t('global.Operation')" width="" align="center">
      <template #default="scope">
        <el-button link type="primary" plain size="small" @click="handleClick('update',scope)">{{
            $t('global.Update')
          }}
        </el-button>
        <el-popconfirm :title="t('message.ConfirmDel')" @confirm="confirmSubmit(scope)" :width="400">
          <template #reference>
            <el-button link type="danger" size="small">{{ $t('global.Delete') }}</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  <!--  新增币种 dialog -->
  <el-dialog v-model="isDialog" :title="dialogTextComputed" width="500" center @close="resetForm">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" status-icon>
      <el-form-item :label="$t('table.ChainName')" prop="chainId">
        <el-select v-model="ruleForm.chainId" :placeholder="$t('global.PleaseSelect')" @change="getTokenList"
                   :disabled="btnType === 'update' ">
          <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.chainId"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="btnType === 'add' ">
        <el-radio-group v-model="radio">
          <el-radio value="2" size="large">{{ t('currencyManagement.Symbol1') }}</el-radio>
          <el-radio value="1" size="large">{{ t('currencyManagement.MainCoin') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('currencyManagement.Name')" prop="name" v-show=" radio === '1' ">
        <el-input v-model.trim="ruleForm.name" type="text"/>
      </el-form-item>
      <el-form-item :label="$t('currencyManagement.Symbol')" prop="symbol" v-show=" radio === '1' ">
        <el-input v-model.trim="ruleForm.symbol" type="text"/>
      </el-form-item>
      <el-form-item :label="$t('currencyManagement.TotalSupply')" prop="totalSupply" v-show=" radio === '1' ">
        <el-input v-model.trim="ruleForm.totalSupply" type="text"/>
      </el-form-item>
      <el-form-item :label="$t('currencyManagement.Decimals')" prop="decimals" v-show=" radio === '1' ">
        <el-input v-model.trim.number="ruleForm.decimals" type="text"/>
      </el-form-item>
      <el-form-item :label="$t('table.Address')" prop="address" v-show=" radio === '2' ">
        <el-input v-model.trim="ruleForm.address" type="text"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose"> {{ $t('global.Cancel') }}</el-button>
        <el-button type="primary" @click="submit" :loading="loading">{{ $t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>

  <!--  删除币种 dialog -->
  <el-dialog v-model="deleteDialog" :title="$t('currencyManagement.DelCurrency')" width="500" center
             @close="deleteDialog = false">
    <div>
      <span>{{ $t('dialog.delTips') }}</span>
    </div>
    <template #footer #default="scope">
      <div class="dialog-footer">
        <el-button @click="deleteDialog = false"> {{ $t('global.Cancel') }}</el-button>
        <el-button type="primary" @click="submitDelete()">{{ $t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted, unref, reactive, watch, computed} from 'vue'
import {Delete, Edit, Plus, Refresh, Search, Upload} from "@element-plus/icons-vue";
import {formatTimestamp} from "@/utils/timeStamp";
import {useUserStore} from "@/stores"
import {ElMessage, ElPagination, ElSwitch, ElTable} from "element-plus";
import {getConfigList, tokenList, createToken, updateToken, deleteToken} from "@/require/api.js"
import {useI18n} from "vue-i18n";

const {t} = useI18n();

onMounted(() => {
  getList()
  getChainList()
  console.log(typeof (radio.value))
})

const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const chainList = ref([])
const loading = ref(false)
const addDialog = ref(false) // 新增币种 dialog
const editDialog = ref(false) // 修改币种 dialog
const deleteDialog = ref(false) // 删除币种 dialog
const isDialog = ref(false) // dialog
const btnType = ref() // 按钮类型  add:新增  update:修改
const radio = ref("2") // 选择添加代币 / 主币    1:主币  2:代币
// $t('currencyManagement.AddCurrency')
// $t('currencyManagement.EditCurrency')
// 计算属性 当btnType 为 update 时, dialogText = $t('currencyManagement.EditCurrency'), 反之  $t('currencyManagement.AddCurrency')
const dialogTextComputed = computed(() => {
  if (btnType.value === 'update') {
    return t('currencyManagement.EditCurrency')
  } else {
    return t('currencyManagement.AddCurrency')
  }
})


const ruleRef = ref(null)
const ruleEditRef = ref(null)
const userStore = useUserStore();

// 获取 TokenList
async function getTokenList(id) {
  console.log(888)
  const chainData = unref(chainList).filter(item => item.chainId === id)
  ruleForm.chainName = chainData[0].chainName
  if (radio.value === "1") {
    // 添加币种时, address 只接受string
    ruleForm.address = String(chainData[0].udunId)
    console.log(ruleForm.address)
  }
}

// 表单 form
const ruleForm = reactive({
  id: '',
  chainName: '',
  chainId: '',
  address: '',
  symbol: '', // 简称
  decimals: undefined,
  name: '', // 全称
  totalSupply: '',
})

// 点击按钮唤出dialog
async function handleClick(type, scope) {
  isDialog.value = true
  if (type === 'add') {
    btnType.value = 'add'
  } else if (type === 'update') {
    console.log(scope.row)
    btnType.value = 'update'
    if (scope.row.Type === '2') {
      //   代币
      radio.value = '2'
      ruleForm.chainId = scope.row.ChainId
      ruleForm.chainName = scope.row.ChainName
      ruleForm.address = scope.row.Address
    } else if (scope.row.Type === '1') {
      //   主币
      radio.value = '1'
      ruleForm.id = scope.row.ID
      ruleForm.chainId = scope.row.ChainId
      ruleForm.chainName = scope.row.ChainName
      ruleForm.name = scope.row.Name
      ruleForm.symbol = scope.row.Symbol
      ruleForm.decimals = scope.row.Decimals
      ruleForm.totalSupply = scope.row.TotalSupply
    }
  }
}

// 提交事件
async function submit() {
  try {
    loading.value = true
    if (btnType.value === 'add') {
      console.log(ruleForm.address)
      const {code, data, msg} = await createToken({
        chainName: ruleForm.chainName,
        chainId: ruleForm.chainId,
        address: ruleForm.address,
        type: radio.value,
        symbol: ruleForm.symbol,
        decimals: ruleForm.decimals,
        totalSupply: ruleForm.totalSupply,
        name: ruleForm.name
      })
      if (code === 200) {
        ElMessage.success(t('message.AddSuccess'))
      } else {
        ElMessage.error(msg)
      }
    } else if (btnType.value === 'update') {
      const {code, data, msg} = await updateToken({
        id: ruleForm.id,
        chainName: ruleForm.chainName,
        chainId: ruleForm.chainId,
        address: ruleForm.address,
        type: radio.value,
        symbol: ruleForm.symbol,
        decimals: ruleForm.decimals,
        totalSupply: ruleForm.totalSupply,
        name: ruleForm.name
      })
      if (code === 200) {
        ElMessage.success(t('message.EditSuccess'))
      } else {
        ElMessage.error(msg)
      }
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
    await getList()
    isDialog.value = false
  }
}


// 提交删除
async function confirmSubmit(scope) {
  try {
    loading.value = true
    const {code, data, msg} = await deleteToken({
      id: scope.row.ID
    })
    if (code === 200) {
      ElMessage.success(t('message.DelSuccess'))
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    deleteDialog.value = false
    await getList()
    loading.value = false
  }
}


// 表单验证规则
const rules = reactive({
  address: [
    {required: true, message: t('message.CallUrlNotNull'), trigger: 'blur'},
  ],
  name: [
    {required: true, message: t('message.MainCoinNameNotNull'), trigger: 'blur'},
  ],
  decimals: [
    {required: true, message: t('message.DecimalsNotNull'), trigger: 'blur'},
  ],
  totalSupply: [
    {required: true, message: t('message.TotalNotNull'), trigger: 'blur'},
  ],
  symbol: [
    {required: true, message: t('message.SymbolAbbNotNull'), trigger: 'blur'},
  ]
})

// 关闭  dialog
const handleClose = () => {
  isDialog.value = false
}

// 查询参数
const queryParams = reactive([
  {
    id: '',
    chainName: '',  // 公链名称
    chainIdMainCoinType:'', // 公链编号 (mainCoinType)
    symbol:'', // 代币名称
    addressCoinType:'', // 合约地址(coinType)
  }
])

// 搜索方法
const onSubmit = (chainName, chainIdMainCoinType, symbol, addressCoinType) => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  getList(chainName, chainIdMainCoinType, symbol, addressCoinType);
}

// 重置查询数据方法
const onReset = () => {
  onClear();
  getList();
}

// 清除  queryParams
const onClear = () => {
  queryParams.id = ''
  queryParams.chainName = ''
  queryParams.chainIdMainCoinType = ''
  queryParams.symbol = ''
  queryParams.addressCoinType = ''
}

// 获取币种列表
async function getList(chainName, chainIdMainCoinType, symbol, addressCoinType) {
  try {
    loading.value = true
    const {code, data, msg} = await tokenList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
      userId: userStore.getUserInfo.userId,
      chainName: chainName ? chainName : '',
      chainId: chainIdMainCoinType ? chainIdMainCoinType : '' ,
      symbol: symbol ? symbol : '',
      address: addressCoinType ? addressCoinType : '',
    })
    if (code === 200) {
      console.log(data)
      tableData.value = data.list
      console.log(tableData.value)
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 重置表单
function resetForm() {
  isDialog.value = false;

  ruleForm.id = undefined
  ruleForm.chainName = undefined
  ruleForm.chainId = undefined
  ruleForm.address = undefined
  ruleForm.symbol = undefined
  ruleForm.decimals = undefined
  ruleForm.name = undefined
  ruleForm.totalSupply = undefined
}

// 获取配置信息
async function getChainList() {
  const {data} = await getConfigList();
  chainList.value = data;
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

</script>

<style scoped lang="less">
.queryBar {
  background-color: #fff;
  margin: .1rem 0;
  padding: .1rem 0;
  box-sizing: border-box;

  .demo-form-inline {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
  }

  .query_btns {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin: .15rem 0 0 0;
  }
}
</style>